import 'dart:io';
import 'dart:typed_data';

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import '../../../core/channel/channel_platform.dart';
import '../../../core/model/local_image_model.dart';
import '../../../core/model/local_video_model.dart';
import '../../shared/math_compute.dart';
import '../../widgets/bilibili_controls.dart';
import 'initialize_up_load.dart';

class HYPublishUpLoad extends StatefulWidget {
  const HYPublishUpLoad({Key? key}) : super(key: key);

  @override
  State<HYPublishUpLoad> createState() => _HYPublishUpLoadState();
}

class _HYPublishUpLoadState extends State<HYPublishUpLoad>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  late TabController tabController;

  List<HYLocalVideoModel> localVideoList = [];
  List<HYLocalImageModel> localImageList = [];

  ///视频、图片、文件widgets
  List<Widget> tabBarViewWidgets = [];

  ///上传的数据类型
  int upLoadFileType = 0;

  ///封面图片缓存
  String imageCache = "";

  ///当前播放的是哪个视频
  int currentVideoIndex = 0;

  @override
  void initState() {
    super.initState();

    ///监听TabBar和TabBarView，两个都要加，一个是点击，一个是左右滑动监听
    tabController = TabController(vsync: this, length: 3);
    tabController.addListener(() {
      upLoadFileType = tabController.index;
      setState(() {});
    });

    ///获取手机本地视频
    const platform = MethodChannel(HYChannel.uploadDataChannel);
    platform.invokeMethod("getVideos").then((value) {
      for (int i = 0; i < value.length; i++) {
        localVideoList.add(HYLocalVideoModel(
          videoLocation: value[i]["videoLocation"],
          videoName: value[i]["videoName"],

          ///这里的duration返回值单位为毫秒，不是秒
          duration: value[i]["duration"] ?? "0",
        ));
      }

      tabBarViewWidgets.add(
        GridView.builder(
          itemCount: localVideoList.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisSpacing: 5.w,
            mainAxisSpacing: 5.h,
            crossAxisCount: 3,
          ),
          itemBuilder: (ctx, index) {
            return FutureBuilder(
              future: getVideoCover(localVideoList[index].videoLocation),
              builder: (ctx, AsyncSnapshot<Uint8List?> snapshot) {
                return GestureDetector(
                  onTap: () {
                    ///点击视频播放视频
                    if (mounted) {
                      setState(() {
                        currentVideoIndex = index;
                      });
                    }
                  },
                  child: snapshot.data != null
                      ? Stack(
                          children: [
                            Container(
                              alignment: Alignment.center,
                              child: Image.memory(
                                snapshot.data!,
                                fit: BoxFit.cover,
                              ),
                            ),
                            Positioned(
                              child: Image.asset(
                                ImageAssets.roundAddPNG,
                                width: 20.w,
                                height: 20.h,
                              ),
                              right: 5.w,
                              top: 5.h,
                            ),
                            Positioned(
                              bottom: 8.h,
                              right: 8.w,
                              child: Text(
                                ///此处要转换单位除以1000变为秒
                                changeToDurationText(double.parse(
                                        localVideoList[index].duration) /
                                    1000.0),
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white,
                                    fontSize: HYAppTheme.xSmallFontSize),
                              ),
                            ),
                          ],
                        )
                      : Container(
                          color: HYAppTheme.norTextColors,
                        ),
                );
              },
            );
          },
        ),
      );

      ///获取手机本地照片
      platform.invokeMethod("getPhotos").then((value) {
        for (int i = 0; i < value.length; i++) {
          localImageList.add(
            HYLocalImageModel(
                value[i]["imageName"] ?? "", value[i]["imageLocation"] ?? ""),
          );
        }

        ///初始化图片
        if (localImageList.isNotEmpty) {
          imageCache = localImageList[0].imageLocation;
        }

        ///TabBarView-图片列表和视频列表、文件列表
        tabBarViewWidgets.add(
          GridView.builder(
            itemCount: localImageList.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisSpacing: 5.w,
              mainAxisSpacing: 5.h,
              crossAxisCount: 3,
            ),
            itemBuilder: (ctx, index) {
              return GestureDetector(
                onTap: () {
                  imageCache = localImageList[index].imageLocation;
                  if (mounted) {
                    setState(() {});
                  }
                },
                child: Image.file(
                  File(localImageList[index].imageLocation),
                  fit: BoxFit.cover,
                ),
              );
            },
          ),
        );

        ///获取本地文件-待补充
        tabBarViewWidgets.add(
          const Center(
            child: Text(
              "文件夹，待写",
              style: TextStyle(color: Colors.white),
            ),
          ),
        );
        setState(() {});
      });
    });
  }

  @override
  void dispose() {
    tabController.removeListener(() {});
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return tabBarViewWidgets.length == 3 &&
            localVideoList.isNotEmpty &&
            localImageList.isNotEmpty
        ? Column(
            children: [
              Stack(
                children: [
                  Container(
                    padding:
                        const EdgeInsets.only(top: 60, left: 20, right: 20).r,
                    // width: MediaQuery.of(context).size.width - 20.w,
                    height: 350.h,
                    child: upLoadFileType == 0
                        ? HYChewieWidget(
                            localVideoList[currentVideoIndex].videoLocation)
                        : Image.file(
                            File(imageCache),
                            fit: BoxFit.contain,
                          ),
                  ),
                  AppBar(
                    backgroundColor: Colors.transparent,
                    leading: GestureDetector(
                      onTap: () {
                        Navigator.of(context).pop();
                      },
                      child: const Icon(
                        Icons.close,
                        color: Colors.white,
                      ),
                    ),
                    actions: [
                      buildUpLoadAction("编辑视频"),
                      buildUpLoadAction("草稿箱"),
                    ],
                  ),
                ],
              ),
              Expanded(
                child: DefaultTabController(
                  length: 3,
                  child: Column(
                    children: [
                      TabBar(
                        labelColor: Colors.white,
                        indicatorColor: HYAppTheme.norTextColors,
                        controller: tabController,
                        tabs: upLoadTabList
                            .map((e) => Tab(
                                  text: e,
                                ))
                            .toList(),
                      ),
                      Expanded(
                          child: TabBarView(
                        children: tabBarViewWidgets,
                        controller: tabController,
                      ))
                    ],
                  ),
                ),
              )
            ],
          )
        : const Center(
            child: CircularProgressIndicator(
            color: HYAppTheme.norMainThemeColors,
          ));
  }

  ///编辑视频、草稿箱
  buildUpLoadAction(String text) {
    return Container(
      alignment: Alignment.center,
      padding: const EdgeInsets.only(right: 20).r,
      decoration:
          BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(30.r))),
      child: Text(
        text,
        style: const TextStyle(color: Colors.white),
      ),
    );
  }

  ///获取视频封面
  Future<Uint8List?> getVideoCover(path) async {
    Uint8List? uint8list = await VideoThumbnail.thumbnailData(
      video: path,
      imageFormat: ImageFormat.PNG,
      // maxWidth: 128,

      ///图片质量
      quality: 10,
    );
    return uint8list;
  }

  @override
  bool get wantKeepAlive => true;
}

class HYChewieWidget extends StatefulWidget {
  ///视频URL
  String url;

  HYChewieWidget(this.url, {Key? key}) : super(key: key);

  @override
  State<HYChewieWidget> createState() => _HYChewieWidgetState();
}

class _HYChewieWidgetState extends State<HYChewieWidget> {
  ///视频播放
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;

  ///是否加载视频完成
  bool isLoadingAccomplished = false;

  @override
  void initState() {
    ///初始化Controller
    _videoPlayerController = VideoPlayerController.file(
      File(widget.url),
    );

    ///这里的.initialize().then作用是为了能获取视频的原始比例，而不会把视频的高度压缩
    _videoPlayerController.initialize().then((value) {
      _chewieController = ChewieController(
        allowMuting: false,
        videoPlayerController: _videoPlayerController,
        autoPlay: false,
        customControls: const HYBilibiliControls(
          showVideoActions: false,
          video: null,
        ),
      );
      isLoadingAccomplished = true;
      if (mounted) {
        setState(() {});
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return isLoadingAccomplished == true
        ? Container(
            padding: EdgeInsets.zero,
            color: HYAppTheme.norTextColors,
            alignment: Alignment.topCenter,
            height: width /
                _chewieController.videoPlayerController.value.aspectRatio,
            child: Stack(
              children: [
                Chewie(
                  controller: _chewieController,
                ),
              ],
            ),
          )
        : Container(
            height: width / 1.77777777777777777,
            color: HYAppTheme.norTextColors,
            child: Center(
              child: SizedBox(
                width: 40.w,
                height: 40.h,
                child: const CircularProgressIndicator(
                  color: HYAppTheme.norMainThemeColors,
                ),
              ),
            ),
          );
  }

  @override
  void dispose() {
    _chewieController.dispose();
    _videoPlayerController.dispose();
    super.dispose();
  }

  ///当url发生改变时，注销再创建，
  ///如果不先注销，必然会内存溢出，多点几个视频，APP就会GG，直接内存爆了
  @override
  void didUpdateWidget(covariant HYChewieWidget oldWidget) {
    if (oldWidget.url != widget.url) {
      if (widget.url == "") return;

      ///关键几步如下
      if (_chewieController != null) _chewieController.dispose();
      if (_videoPlayerController != null) _videoPlayerController.dispose();

      ///初始化视频数据
      _videoPlayerController = VideoPlayerController.file(
        File(widget.url),
      );
      _videoPlayerController.initialize().then((value) {
        _chewieController = ChewieController(
          allowMuting: false,
          videoPlayerController: _videoPlayerController,
          autoPlay: true,
          customControls: const HYBilibiliControls(
            showVideoActions: false,
            video: null,
          ),
        );
        isLoadingAccomplished = true;
        if (mounted) {
          setState(() {});
        }
      });
    }
    super.didUpdateWidget(oldWidget);
  }
}
